<template>
  <div class="app-container">

    <div class="filter-container">
      <el-select v-model="noticeQuery.building" placeholder="请选择区域" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in buildingOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="noticeQuery.importance" placeholder="请选择重要等级" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in importanceOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="noticeQuery.title" placeholder="标题" clearable style="width: 300px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="noticeQuery.begin" type="datetime" placeholder="开始时间" class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="noticeQuery.end" type="datetime" placeholder="结束时间" class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="区域" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.building }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="发布时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.publishTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="重要等级" width="200">
        <template slot-scope="scope">
          <el-rate
            v-model="scope.row.importance"
            :max="3"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :low-threshold="1"
            :high-threshold="3"
            style="display:inline-block"
          />
        </template>
      </el-table-column>
      <el-table-column label="标题" width="400">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="medium" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="medium" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" top="0vh" width="75%">
      <el-form ref="dataForm" :model="notice" :rules="rules" class="form-container">

        <div class="createPost-main-container">
          <el-row>

            <el-col :span="24">
              <el-form-item style="margin-bottom: 40px;" prop="title">
                <MDinput v-model="notice.title" :maxlength="100" name="name" required>
                  Title
                </MDinput>
              </el-form-item>

              <div class="postInfo-container">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="区域" prop="building">
                      <el-select v-model="notice.building" placeholder="请选择区域" clearable>
                        <el-option v-for="item in buildingOptions" :key="item.id" :label="item.name" :value="item.id" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label-width="120px" label="发布时间:" prop="publishTime" class="postInfo-container-item">
                      <el-date-picker v-model="notice.publishTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择发布时间" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label-width="120px" prop="importance" label="Importance:" class="postInfo-container-item">
                      <el-rate
                        v-model="notice.importance"
                        :max="3"
                        :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                        :low-threshold="1"
                        :high-threshold="3"
                        style="display:inline-block"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>

          <el-form-item prop="content" style="margin-bottom: 30px;">
            <Tinymce ref="editor" v-model="notice.content" :height="400" />
          </el-form-item>

        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, remove, save, update, getNotice, buildingList } from '@/api/notice'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Tinymce from '@/components/Tinymce'
import MDinput from '@/components/MDinput'

export default {
  components: { Pagination, Tinymce, MDinput },
  directives: { waves },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      listLoading: true,
      total: 0,
      page: 1,
      limit: 10,
      noticeQuery: {
        building: '',
        importance: '',
        title: '',
        begin: '',
        end: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      notice: {
        id: '',
        building: '',
        importance: '', // 重要程度
        title: '', // 文章题目
        publishTime: '', // 发布时间
        content: '' // 文章内容
      },
      dialogFormVisible: false,
      rules: {
        building: [{ required: true, message: '区域不能为空', trigger: 'blur' }],
        importance: [{ required: true, message: '重要程度不能为空', trigger: 'blur' }],
        publishTime: [{ required: true, message: '发布时间不能为空', trigger: 'blur' }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }]
      },
      buildingOptions: [],
      importanceOptions: [{ label: '1', key: 1 }, { label: '2', key: 2 }, { label: '3', key: 3 }]
    }
  },
  created() {
    this.getList()
    buildingList().then((response) => {
      this.buildingOptions = response.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.page, this.limit, this.noticeQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.page = 1
      this.getList()
    },
    handleCreate() {
      this.resetNotice()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetNotice() {
      this.notice = {
        id: '',
        building: '',
        buildingDesc: '',
        title: '', // 文章题目
        importance: 0, // 重要程度
        publishTime: '', // 发布时间
        content: '' // 文章内容
      }
    },
    setBuilding(data) {
      this.buildingOptions.find((item) => {
        if (item.id === data.building) {
          data.building = item.name
          return
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          save(this.notice).then((response) => {
            this.setBuilding(response.data)
            this.list.unshift(response.data)
            this.$notify({
              title: 'Success',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    async handleUpdate(row) {
      // 获取宿舍信息
      const res = await getNotice(row.id)
      this.notice = res.data
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          update(this.notice).then((response) => {
            this.setBuilding(response.data)
            const index = this.list.findIndex(v => v.id === response.data.id)
            this.list.splice(index, 1, response.data)
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
      remove(row.id)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-main-container {
  padding: 40px 45px 20px 50px;
  .postInfo-container {
    position: relative;
    @include clearfix;
    margin-bottom: 10px;
    .postInfo-container-item {
      float: left;
    }
  }
}
.word-counter {
  width: 40px;
  position: absolute;
  right: 10px;
  top: 0px;
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
